import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
  Modal,
  Pressable,
  Dimensions,
} from 'react-native';

/**
 * DropdownButton 组件用于创建一个下拉选择框。
 * 
 * @param {Object} props - 组件的属性对象。
 * @param {Array<string>} props.options - 下拉框的选项列表。
 * @param {Function} [props.onSelect] - 选择选项时触发的回调函数，接收选中的值作为参数。
 * @param {string} [props.defaultValue] - 下拉框的默认显示值。
 * @param {Object} [props.HomeStyle={}] - 自定义的容器样式。
 * 
 * @returns {JSX.Element} - 渲染的下拉选择框组件。
 * 
 * @注意事项
 * - `options` 数组必须包含至少一个选项。
 * - 当屏幕旋转时，下拉框位置会自动调整，但可能需要根据实际情况进行微调。
 */
const DropdownButton = ({ options, onSelect, defaultValue, HomeStyle = {} }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedValue, setSelectedValue] = useState(defaultValue || options[0]);
  const containerRef = useRef(null);
  const buttonRef = useRef(null);
  const dropdownRef = useRef(null);
  const [dropdownPosition, setDropdownPosition] = useState({ x: 0, y: 0, width: 0 });

  // 切换下拉框
  const toggleDropdown = () => {
    setIsOpen(!isOpen);
  };

  // 选择选项
  const handleSelect = (value) => {
    setSelectedValue(value);
    onSelect?.(value);
    setIsOpen(false);
  };

  // 点击外部关闭
  const handleOutsidePress = () => {
    setIsOpen(false);
  };

  // 计算下拉框位置
  useEffect(() => {
    if (buttonRef.current && isOpen) {
      // 获取按钮相对于屏幕的位置
      buttonRef.current.measureInWindow((x, y, width, height) => {
        setDropdownPosition({ x, y: y + height, width });
      });
    }
  }, [isOpen]);

  // 屏幕旋转处理
  useEffect(() => {
    const handleResize = () => {
      if (isOpen && buttonRef.current) {
        buttonRef.current.measureInWindow((x, y, width, height) => {
          setDropdownPosition({ x, y: y + height, width });
        });
      }
    };

    const subscription = Dimensions.addEventListener('change', handleResize);
    return () => subscription.remove();
  }, [isOpen]);

  return (
    <View ref={containerRef} style={[styles.container, HomeStyle]}>
      {/* 下拉按钮 - 添加ref */}
      <TouchableOpacity
        ref={buttonRef}
        style={[styles.button, isOpen && styles.buttonActive]}
        onPress={toggleDropdown}
      >
        <Text style={styles.text} numberOfLines={1}>
          {selectedValue}
        </Text>
      </TouchableOpacity>

      {/* 下拉列表 */}
      {isOpen && (
        <Modal
          transparent={true}
          visible={isOpen}
          animationType="fade"
          onRequestClose={handleOutsidePress}
        >
          <Pressable
            style={styles.overlay}
            onPress={handleOutsidePress}
          >
            <View
              style={[
                styles.dropdownContainer,
                {
                  left: dropdownPosition.x,
                  top: dropdownPosition.y,
                  width: dropdownPosition.width,
                }
              ]}
              ref={dropdownRef}
              onStartShouldSetResponder={() => true}
              onResponderTerminationRequest={() => false}
            >
              <ScrollView
                style={styles.dropdown}
                keyboardShouldPersistTaps="always"
              >
                {options.map((option, index) => (
                  <TouchableOpacity
                    key={index}
                    style={[styles.item, selectedValue === option && styles.itemSelected]}
                    onPress={() => handleSelect(option)}
                  >
                    <Text style={[styles.itemText, selectedValue === option && styles.itemTextSelected]}>
                      {option}
                    </Text>
                  </TouchableOpacity>
                ))}
              </ScrollView>
            </View>
          </Pressable>
        </Modal>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: '100%',
  },
  button: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
    justifyContent: 'space-between',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#ddd',
    flexDirection: 'row',
    height: 40,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2,
  },
  buttonActive: {
    borderBottomLeftRadius: 0,
    borderBottomRightRadius: 0,
    borderColor: '#4285f4',
  },
  text: {
    fontSize: 14,
    color: '#333',
    maxWidth: '80%',
  },
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.01)',
  },
  dropdownContainer: {
    position: 'absolute',
    zIndex: 100,
  },
  dropdown: {
    backgroundColor: '#fff',
    borderWidth: 1,
    borderColor: '#ddd',
    borderBottomLeftRadius: 8,
    borderBottomRightRadius: 8,
    borderTopWidth: 0,
    maxHeight: 200,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 3,
    elevation: 3,
  },
  item: {
    padding: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  itemSelected: {
    backgroundColor: '#f5f8ff',
  },
  itemText: {
    fontSize: 14,
    color: '#333',
  },
  itemTextSelected: {
    fontWeight: '500',
    color: '#4285f4',
  },
});

export default DropdownButton;  